<!--
  @Descripttion:用户中心-账号设置（修改手机号）
  @Author：yejianbo
  @Date：2022年05月26日 12:35:40
-->
<template>
  <pageCom>
    <div class="content-page">
      <div class="content">
        <div class="nav-com">
          <el-breadcrumb
            separator-class="el-icon-arrow-right"
            style="margin-bottom: 20px"
          >
            <el-breadcrumb-item :to="{ name: 'home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item :to="{ name: 'userCenter' }">
              用户中心
            </el-breadcrumb-item>
            <el-breadcrumb-item>
              <span style="color: #3d6cb0">{{
                $route.meta.title || "--"
              }}</span>
            </el-breadcrumb-item>
          </el-breadcrumb>
        </div>
        <div class="content-title">更换手机号</div>
        <div class="main-item">
          <p class="tips-text">
            *修改后，请使用新的手机号登录数据学徒，当前手机号无法再登录数据学徒实习平台
          </p>
          <div class="row">
            <div class="left">当前手机号码</div>
            <div class="right">
              <!-- 脱敏展示 -->
              <p class="old-phone">{{ formData.oldPhone | hideNum }}</p>
            </div>
          </div>
          <div class="row">
            <div class="left">新手机号码</div>
            <el-select
              size="mini"
              style="width: 100px; margin-right: 12px"
              v-model="formData.prexNum"
            >
              <el-option
                v-for="(item, index) in nationPhoneNumber"
                :key="index"
                :value="item.phone_code"
                :label="'+' + item.phone_code"
                >{{ item.chinese_name }}</el-option
              >
            </el-select>
            <el-input
              type="number"
              size="mini"
              v-model="formData.newPhone"
              style="width: 200px"
              oninput="if(value.length>20)value=value.slice(0,20)"
              @blur="checkParams('newPhone')"
            />
            <div class="error-msg" v-if="rules.newPhone">请输入新手机号</div>
          </div>
          <div class="row">
            <div class="left">图形验证码</div>
            <el-input
              v-model="formData.imgCode"
              size="mini"
              style="width: 200px; vertical-align: middle"
              @blur="checkParams('imgCode')"
            />
            <img
              class="code-img"
              :src="codeImgUrl"
              v-imgError
              alt=""
              @click="getCode"
            />
            <div class="resend" @click="getCode">换一张</div>
            <div class="error-msg" v-if="rules.imgCode">请输入图形验证码</div>
          </div>
          <div class="row">
            <div class="left">短信验证码</div>
            <el-input
              type="number"
              size="mini"
              v-model="formData.msgCode"
              style="width: 200px; vertical-align: middle"
              oninput="if(value.length>6)value=value.slice(0,6)"
              @blur="checkParams('msgCode')"
            />
            <el-button
              @click.native="handleMsg"
              :disabled="msgDisabled"
              size="medium"
              style="
                margin: 0 10px;
                position: relative;
                height: 28px;
                line-height: 28px;
                padding: 0 10px;
              "
              type="primary"
              >{{ count ? count + "s" : "发送短信" }}</el-button
            >
            <div class="error-msg" v-if="rules.msgCode">请输入短信验证码</div>
          </div>
        </div>
        <div class="btns" @click="confirmHandle">确定修改</div>
      </div>
    </div>
    <!-- 阿里认证弹窗 -->
    <div class="showAuthentication" v-if="showAuthentication">
      <div class="showAuthenticationBox">
        <div class="title">实名认证</div>
        <div class="content" v-loading="showLoading">
          {{ authenticationTitle }}
        </div>
        <div class="btns">
          <div class="cancel" @click="showAuthentication = !showAuthentication">
            取消
          </div>
          <div
            class="submit"
            :class="authenticationTitle != '认证成功' ? 'uns' : ''"
            @click="sendMsg(authenticationTitle != '认证成功')"
          >
            提交
          </div>
        </div>
      </div>
    </div>
  </pageCom>
</template>

<script>
import { getImgCode, changeStudentPhone, isRealName } from "../../request/api";
import { nationPhoneNumber } from "@/utils/frontDataDict.js";
import pageCom from "@/components/page/index.vue";
import { mapState } from "vuex";
import { sendStudentMsg } from "../../request/api";
import { mapMutations } from "vuex";
export default {
  // 组件名称
  name: "setAccount",
  // 局部注册的组件
  components: { pageCom },
  // 组件状态值
  data() {
    return {
      msgDisabled: false,
      nationPhoneNumber: nationPhoneNumber,
      formData: {
        prexNum: "86", // 手机区号
        oldPhone: "", // 旧手机
        newPhone: "", // 新手机
        imgCode: "", // 图形验证码
        msgCode: "", // 短信验证码
      },
      showAuthentication: false,
      showLoading: false,
      authenticationTitle: "认证中",
      uuid: "",
      rules: {
        newPhone: false,
        imgCode: false,
        msgCode: false,
      },
      codeImgUrl: "",
      timeInstance: null,
      count: null,
      loading: false,
    };
  },

  computed: {
    ...mapState(["USER_INFO", "isChina"]),
  },
  filters: {
    hideNum(num) {
      return num.substring(0, 3) + "****" + num.substring(7, 11);
    },
  },
  // 组件方法
  methods: {
    ...mapMutations(["loginOut"]),
    sendMsg(falg = false) {
      if (falg) return;
      this.showAuthentication = false;
      this.authenticationTitle = "认证中";
      let { newPhone, imgCode, prexNum } = this.formData;
      let param = {
        code: imgCode,
        mobile: prexNum + "-" + newPhone,
        scene: 4,
        uuid: this.uuid,
      };
      sendStudentMsg(param)
        .then((res) => {
          if (res.code === 0 && res.data) {
            if (this.timeInstance !== null) {
              clearInterval(this.timeInstance);
            }
            this.count = 59;
            this.msgDisabled = true;
            this.timeInstance = setInterval(() => {
              this.count--;
              if (this.count <= 0) {
                clearInterval(this.timeInstance);
                this.count = null;
                this.timeInstance = null;
                this.msgDisabled = false;
              }
            }, 1000);
          } else {
            this.$message.error(res.msg);
            clearInterval(this.timeInstance);
            this.count = null;
            this.timeInstance = null;
            this.msgDisabled = false;
            this.formData.imgCode = "";
            this.getCode();
          }
        })
        .catch(() => {
          clearInterval(this.timeInstance);
          this.count = null;
          this.timeInstance = null;
          this.msgDisabled = false;
          this.formData.imgCode = "";
          this.getCode();
        });
    },
    handleMsg() {
      let { newPhone, oldPhone, prexNum } = this.formData;
      if (newPhone === oldPhone) {
        this.$message.warning("不可修改为相同手机号");
        return;
      }
      if (!this.checkParams("newPhone") && !this.checkParams("imgCode")) {
        if (this.msgDisabled) return;

        if (prexNum == "86" && newPhone.length == 11) {
          //如果是大陆手机号，则需要实名认证
          this.showLoading = true;
          this.showAuthentication = true;
          isRealName({
            cardNo: this.USER_INFO.cardNo,
            phone: newPhone,
            userName: this.USER_INFO.nickname,
          })
            .then((res) => {
              this.showLoading = false;
              if (res.data) {
                this.authenticationTitle = "认证成功";
              } else {
                this.authenticationTitle = "认证失败";
              }
            })
            .catch((err) => {
              this.showLoading = false;
            });
          return;
        }
        this.sendMsg();
      }
    },
    checkParams(key) {
      switch (key) {
        case "newPhone":
          let phoneReg = /^[0-9]{1,}/;
          if (phoneReg.test(this.formData.newPhone)) {
            this.rules.newPhone = false;
          } else {
            this.rules.newPhone = true;
          }
          break;
        case "imgCode":
          if (this.formData.imgCode !== "") {
            this.rules.imgCode = false;
          } else {
            this.rules.imgCode = true;
          }
          break;
        case "msgCode":
          if (this.formData.msgCode !== "") {
            this.rules.msgCode = false;
          } else {
            this.rules.msgCode = true;
          }
          break;
      }
      return this.rules[key];
    },
    getCode() {
      getImgCode().then((res) => {
        if (res.data) {
          res.data.img = "data:image/jpeg;base64," + res.data.img;
          this.codeImgUrl = res.data.img;
          this.uuid = res.data.uuid;
        }
      });
    },
    changeFun(param) {
      this.loading = true;
      changeStudentPhone(param).then((res) => {
        this.loading = false;
        if (res.code === 0 && res.data) {
          this.$message.success("账户修改成功，请重新登录");
          this.loginOut(() => {
            this.$router.push({ name: "login" });
          });
        } else {
          this.$message.error(res.msg);
        }
      });
    },
    confirmHandle() {
      if (
        !this.checkParams("newPhone") &&
        !this.checkParams("imgCode") &&
        !this.checkParams("msgCode")
      ) {
        if (this.loading) return;
        let { newPhone, oldPhone, msgCode, prexNum } = this.formData;
        let param = {
          code: msgCode,
          newMobile: newPhone,
          oldMobile: oldPhone,
          scene: 4,
        };
        this.changeFun(param);
      }
    },
  },
  created() {
    this.formData.oldPhone = localStorage.getItem("userMobile");
    this.getCode();
  },
  mounted() {},
};
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="less" scoped>
.content-page {
  position: relative;
  width: 100%;
  overflow-y: auto;
  .content {
    position: relative;
    width: 100%;
    min-height: calc(100vh - 100px);
    margin: 0 auto;
    background: #fff;
    position: relative;
    .content-title {
      font-size: 28px;
      font-weight: 600;
      color: #37383d;
      line-height: 40px;
      margin-bottom: 15px;
    }
    .explan-content {
      width: 180px;
      height: 210px;
      font-size: 24px;
      color: #37383d;
      line-height: 33px;
      text-align: center;
      margin-top: 25px;
    }
    .main-item {
      display: flex;
      flex-direction: column;
      .tips-text {
        font-size: 14px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #fc9c21;
        line-height: 28px;
        margin-bottom: 15px;
      }
    }
    .row {
      position: relative;
      display: flex;
      flex-flow: row nowrap;
      margin-bottom: 15px;
      justify-content: flex-start;
      .left {
        width: 120px;
        text-align: left;
        line-height: 24px;
        font-size: 14px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #37383d;
      }
      .right {
        flex: 1;
        .old-phone {
          position: relative;
          font-size: 12px;
          line-height: 28px;
          font-family: PingFangSC-Regular, PingFang SC;
          font-weight: 400;
          color: #37383d;
        }
      }
      .code-img {
        display: inline-block;
        height: 40px;
        margin: 0 10px 0 10px;
        cursor: pointer;
      }
      .resend {
        font-size: 20px;
        font-family: PingFangSC-Medium, PingFang SC;
        font-weight: 500;
        color: #54cf52;
        height: 28px;
        line-height: 28px;
        cursor: pointer;
      }
      .error-msg {
        position: relative;
        font-size: 12px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #fc9c21;
        height: 28px;
        line-height: 28px;
        margin-left: 10px;
        padding-left: 21px;
        &::before {
          content: "";
          display: block;
          width: 16px;
          height: 16px;
          background: url("../../assets/images/user/error.png") no-repeat center
            center / cover;
          position: absolute;
          left: 0;
          top: 50%;
          margin-top: -8px;
        }
      }
    }
    .btns {
      position: relative;
      width: 464px;
      height: 40px;
      margin: 0 auto;
      background: #4677b9;
      border-radius: 4px;
      display: flex;
      justify-content: center;
      align-items: center;
      font-size: 20px;
      font-weight: 600;
      color: #ffffff;
      cursor: pointer;
      margin-top: 58px;
      &:first-child {
        margin-right: 60px;
      }
      &:hover {
        color: #2f8efe;
        box-shadow: 0px 4px 15px 0px rgba(0, 0, 0, 0.08);
      }
    }
  }
}

.showAuthentication {
  position: fixed;
  z-index: 2014;
  width: 100%;
  height: 100%;
  left: 0;
  top: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  background: rgba(0, 0, 0, 0.3);
  .showAuthenticationBox {
    width: 360px;
    height: 241px;
    padding: 66px 30px 90px;
    border-radius: 12px;
    background: #fff;
    position: relative;
    .content {
      width: 100%;
      height: 100%;
      display: flex;
      justify-content: center;
      align-items: center;
      font-size: 15px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #37383d;
      line-height: 21px;
    }
    .content2 {
      width: 100%;
      display: flex;
      justify-content: center;
      align-items: center;
      font-size: 15px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #37383d;
      line-height: 21px;
    }
    .title {
      position: absolute;
      width: 100%;
      left: 0;
      display: flex;
      justify-content: center;
      align-items: center;
      font-size: 18px;
      font-family: PingFangSC-Medium, PingFang SC;
      font-weight: 500;
      color: #37383d;
      line-height: 25px;
      top: 25px;
    }
    .title2 {
      font-size: 14px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #37383d;
      line-height: 20px;
      margin-bottom: 12px;
    }
    .btns {
      width: 100%;
      height: 40px;
      position: absolute;
      bottom: 40px;
      left: 0;
      display: flex;
      justify-content: space-between;
      padding: 0 40px;
      & > div {
        width: 130px;
        height: 40px;
        display: flex;
        justify-content: center;
        align-items: center;
        font-size: 14px;
        font-size: 14px;
        font-family: PingFangSC-Semibold, PingFang SC;
        font-weight: 600;
        color: #4677b9;
        border: 1px solid #4677b9;
        border-radius: 2px;
        cursor: pointer;
        &.submit {
          background: #4677b9;
          color: #fff;
          border: none;
          &.uns {
            background: #ccc;
            cursor: not-allowed;
          }
        }
      }
    }
  }
}
</style>
